package com.laiketui.plugin.common.service.plugin.member;

import com.alibaba.fastjson.JSONArray;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.core.utils.tool.DateUtil;
import com.laiketui.plugin.common.domain.base.SignRecordModel;
import com.laiketui.plugin.common.domain.base.User;
import com.laiketui.plugin.common.domain.base.order.OrderDataModel;
import com.laiketui.plugin.common.domain.exception.LaiKeAPIException;
import com.laiketui.plugin.common.domain.lktconst.DictionaryConst;
import com.laiketui.plugin.common.domain.lktconst.ErrorCode;
import com.laiketui.plugin.common.domain.vo.member.BonusPointsConfigVo;
import com.laiketui.plugin.common.domain.vo.member.BuyMemberVo;
import com.laiketui.plugin.common.domain.vo.member.MemberOrderVo;
import com.laiketui.plugin.common.interfaces.plugin.member.PubliceMemberService;
import com.laiketui.plugin.common.mapper.MemberConfigMapper;
import com.laiketui.plugin.common.mapper.SignRecordModelMapper;
import com.laiketui.plugin.common.mapper.UserBaseMapper;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 会员公共方法
 *
 * @author sunH_
 */
@Service
public class PubliceMemberServiceImpl implements PubliceMemberService {

    private final Logger logger = LoggerFactory.getLogger(PubliceMemberServiceImpl.class);

    @Autowired
    private MemberConfigMapper memberConfigMapper;

    @Autowired
    private UserBaseMapper userBaseMapper;

    @Autowired
    private SignRecordModelMapper signRecordModelMapper;

    @Override
    public void sendPoints(User user, Integer memberType, Integer storeId, OrderDataModel orderDataModel) throws LaiKeAPIException {
        try {
            //会员插件配置
            Map<String, Object> config = memberConfigMapper.getConfig(storeId);
            //开会员赠送积分
            String memberTypeDesc = "";
            switch (memberType){
                case 1:
                    memberTypeDesc = "月卡";
                    break;
                case 2:
                    memberTypeDesc = "季卡";
                    break;
                case 3:
                    memberTypeDesc = "年卡";
                    break;
                default:
                    break;
            }
            Integer bonusPointsOpen = MapUtils.getInteger(config, "bonus_points_open");
            if (bonusPointsOpen == DictionaryConst.WhetherMaven.WHETHER_OK){
                String bonusPointsConfig = MapUtils.getString(config, "bonus_points_config");
                List<BonusPointsConfigVo> bonusPointsConfigVos = JSONArray.parseArray(bonusPointsConfig, BonusPointsConfigVo.class);
                for (BonusPointsConfigVo vo : bonusPointsConfigVos){
                    if (vo.getOpenMethod().equals(memberTypeDesc)){
                        //积分明细
                        SignRecordModel signRecordModel = new SignRecordModel();
                        signRecordModel.setStore_id(storeId);
                        signRecordModel.setUser_id(user.getUser_id());
                        signRecordModel.setSign_score(vo.getPoints());
                        signRecordModel.setTotal_score(user.getScore());
                        signRecordModel.setRecord(user.getUser_id() + "开通" + memberTypeDesc + "会员获得" + vo.getPoints() + "积分");
                        signRecordModel.setType(SignRecordModel.ScoreType.OPEN_MEMBER);
                        signRecordModel.setsNo(orderDataModel.getTrade_no());
                        signRecordModel.setScore_invalid(null);
                        signRecordModel.setSign_time(new Date());
                        signRecordModelMapper.insertSelective(signRecordModel);

                        user.setScore(user.getScore() + vo.getPoints());
                        userBaseMapper.updateByPrimaryKey(user);

                    }
                }
            }
        } catch (com.laiketui.core.exception.LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("开通会员赠送积分 异常", e);
            throw new com.laiketui.core.exception.LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "sendPoints");
        }
    }

    @Override
    public void doublePoints(User user, Integer storeId, BigDecimal price, String sNo) throws LaiKeAPIException {
        try {
            //会员插件配置
            Map<String, Object> config = memberConfigMapper.getConfig(storeId);
            Integer id = MapUtils.getInteger(config, "id");
            if (id != null){
                Integer birthdayOpen = MapUtils.getInteger(config, "birthday_open");
                if (birthdayOpen.equals(DictionaryConst.WhetherMaven.WHETHER_OK)){
                    if (user.getBirthday() != null){
                        String userBirthday = DateUtil.dateFormate(user.getBirthday(), GloabConst.TimePattern.YMD);
                        String today = DateUtil.dateFormate(new Date(), GloabConst.TimePattern.YMD);
                        if (today.equals(userBirthday)){
                            Integer pointsMultiple = MapUtils.getInteger(config, "points_multiple");
                            BigDecimal multiply = price.multiply(new BigDecimal(pointsMultiple));
                            //积分明细
                            SignRecordModel signRecordModel = new SignRecordModel();
                            signRecordModel.setStore_id(storeId);
                            signRecordModel.setUser_id(user.getUser_id());
                            signRecordModel.setSign_score(multiply.intValue());
                            signRecordModel.setTotal_score(user.getScore());
                            signRecordModel.setRecord(user.getUser_id() + "会员生日特权奖励获得" + multiply.intValue() + "积分");
                            signRecordModel.setType(SignRecordModel.ScoreType.MEMBER_BIRTHDAY);
                            signRecordModel.setsNo(sNo);
                            signRecordModel.setScore_invalid(null);
                            signRecordModel.setSign_time(new Date());
                            signRecordModelMapper.insertSelective(signRecordModel);
                            user.setScore(user.getScore() + multiply.intValue());
                            userBaseMapper.updateByPrimaryKey(user);
                        }
                    }
                }
            }
        } catch (com.laiketui.core.exception.LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("会员生日特权奖励 异常", e);
            throw new com.laiketui.core.exception.LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "doublePoints");
        }
    }

    @Override
    public MemberOrderVo getOrderData(User user, BuyMemberVo vo) throws LaiKeAPIException {
        MemberOrderVo memberOrderVo = new MemberOrderVo();
        try {
            memberOrderVo.setStoreId(vo.getStoreId());
            memberOrderVo.setUserId(user.getUser_id());
            memberOrderVo.setAmount(vo.getAmount());
            memberOrderVo.setMemberType(vo.getMemberType());
            if (user.getGrade().equals(User.MEMBER) && String.valueOf(DictionaryConst.WhetherMaven.WHETHER_NO).equals(user.getIs_out())){
                logger.debug("会员已存在到期时间为{}", DateUtil.dateFormate(user.getGrade_end(), GloabConst.TimePattern.YMDHMS));
                memberOrderVo.setStartTime(DateUtil.dateFormate(user.getGrade_end(), GloabConst.TimePattern.YMDHMS));
                switch (vo.getMemberType()){
                    case 1:
                        logger.debug("会员已存在到期时间增加30天{}", DateUtil.dateFormate(DateUtil.getAddDate(user.getGrade_end(), 30), GloabConst.TimePattern.YMDHMS));
                        memberOrderVo.setEndTime(DateUtil.dateFormate(DateUtil.getAddDate(user.getGrade_end(), 30), GloabConst.TimePattern.YMDHMS));
                        break;
                    case 2:
                        logger.debug("会员已存在到期时间增加90天{}", DateUtil.dateFormate(DateUtil.getAddDate(user.getGrade_end(), 90), GloabConst.TimePattern.YMDHMS));
                        memberOrderVo.setEndTime(DateUtil.dateFormate(DateUtil.getAddDate(user.getGrade_end(), 90), GloabConst.TimePattern.YMDHMS));
                        break;
                    case 3:
                        logger.debug("会员已存在到期时间增加365天{}", DateUtil.dateFormate(DateUtil.getAddDate(user.getGrade_end(), 365), GloabConst.TimePattern.YMDHMS));
                        memberOrderVo.setEndTime(DateUtil.dateFormate(DateUtil.getAddDate(user.getGrade_end(), 365), GloabConst.TimePattern.YMDHMS));
                        break;
                    default:
                        break;
                }
            }else {
                memberOrderVo.setStartTime(DateUtil.dateFormate(new Date(), GloabConst.TimePattern.YMDHMS));
                switch (vo.getMemberType()){
                    case 1:
                        memberOrderVo.setEndTime(DateUtil.dateFormate(DateUtil.getAddDate(new Date(), 30), GloabConst.TimePattern.YMDHMS));
                        break;
                    case 2:
                        memberOrderVo.setEndTime(DateUtil.dateFormate(DateUtil.getAddDate(new Date(), 90), GloabConst.TimePattern.YMDHMS));
                        break;
                    case 3:
                        memberOrderVo.setEndTime(DateUtil.dateFormate(DateUtil.getAddDate(new Date(), 365), GloabConst.TimePattern.YMDHMS));
                        break;
                    default:
                        break;
                }
            }
            memberOrderVo.setPayType(vo.getPayType());
            memberOrderVo.setCouponId(vo.getCouponId());
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("会员生日特权奖励 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "doublePoints");
        }
        return memberOrderVo;
    }
}

